using System;
using System.Threading.Tasks;

using Godot;

using MatchThree.Enums;

public partial class Sweet : Control
{
    public CookieType CookieType { get; set; }

    public int X { get; private set; }
    public int Y { get; private set; }

    public AnimationPlayer Animation { get; set; }

    [Signal] public delegate void SweetClearEventHandler();

    public override void _Ready()
    {
        Animation = GetNode<AnimationPlayer>("AnimationPlayer");
        Animation.AnimationFinished += Animation_AnimationFinished;
    }

    public void SetGrid(int x, int y)
    {
        X = x;
        Y = y;
    }

    public bool IsAdjoin(Sweet sweet)
    {
        if (sweet.X == X)
        {
            if (Math.Abs(sweet.Y - Y) == 1)
            {
                return true;
            }
        }

        if (sweet.Y == Y)
        {
            if (Math.Abs(sweet.X - X) == 1)
            {
                return true;
            }
        }
        return false;
    }

    public bool EqualsType(Sweet sweet)
    {
        return CookieType == sweet.CookieType;
    }

    public void SetCookieTexture(CookieType cookieType)
    {
        CookieType = cookieType;
        CompressedTexture2D imgTexture = null;
        switch (cookieType)
        {
            case CookieType.Blue:
                imgTexture = GD.Load<CompressedTexture2D>("res://Assets/Cookie/Blue.jpg");
                break;

            case CookieType.Green:
                imgTexture = GD.Load<CompressedTexture2D>("res://Assets/Cookie/Green.jpg");
                break;

            case CookieType.Pink:
                imgTexture = GD.Load<CompressedTexture2D>("res://Assets/Cookie/Pink.jpg");
                break;

            case CookieType.Purple:
                imgTexture = GD.Load<CompressedTexture2D>("res://Assets/Cookie/Purple.jpg");
                break;

            case CookieType.Orange:
                imgTexture = GD.Load<CompressedTexture2D>("res://Assets/Cookie/Orange.jpg");
                break;

            case CookieType.Yellow:
                imgTexture = GD.Load<CompressedTexture2D>("res://Assets/Cookie/Yellow.jpg");
                break;
        }
        var cookie = GetNode<TextureRect>("TextureRect1");
        cookie.Texture = imgTexture;
    }

    public async Task Die()
    {
        Animation.Play("start");
        GD.Print("动画开始");
        await ToSignal(Animation, AnimationPlayer.SignalName.AnimationFinished);
        GD.Print("动画结束");
    }

    private void Animation_AnimationFinished(StringName animationName)
    {
        GD.Print("动画关闭");
        if (animationName == "start")
        {
            EmitSignal(SignalName.SweetClear);
            QueueFree();
        }
    }
}